import { usingProgress } from '../../functionalComponent';
import { iup } from '../../util';
import { NGLang, showFlowInfo, showFlowInfoByPiId, wfAlert } from './util';
import { openWorkFlowBatchStartWin } from './WorkFlowBatchStartWin';
import { openWorkFlowStartWin } from './WorkFlowStartWin';

/**
 * 送审
 * @param params
 * @private
 */
async function _startFlowWithPdKey(params: any) {
  const { appCode, bizCode, dataId, pdkey, cuNo, orgNo, cancelback, processType, formApprovalUserNo } = params;
  if (!appCode || !bizCode) {
    await wfAlert(NGLang.alertTitle, NGLang.paramError);
    return;
  }

  const data: any = { appCode, bizCode, dataId, pdkey, cuNo, orgNo };
  if (pdkey) {
    data.pdkey = Array.isArray(pdkey) ? pdkey.join(',') : pdkey;
  }
  if (orgNo) {
    data.orgNo = orgNo;
  }
  const res = await usingProgress(() =>
    iup.request.body({
      url: '/workflow/processDefinition/getStartProcessExecutionInfo',
      data: { appCode, bizCode, dataId, cuNo, orgNo, processType }
    })
  );
  if (res.code === 0) {
    const processDefinitions: any = res.data;
    // setNGLang({ ...res.data.processDefinitions[0] });
    if (processDefinitions.hasRuninfgFlow) {
      await wfAlert(NGLang.alertTitle, NGLang.bizHasRuningProcInst);
      cancelback?.();
      return;
    }
    await openWorkFlowStartWin({
      ...params,
      data: processDefinitions,
      autoStart: !!pdkey || processDefinitions.autostart
    });
  } else {
    await wfAlert(NGLang.getPdListError, res.errorMsg);
  }
}

/**
 * 从流程导航中获取流程定义
 * @param bizType
 * @param bizPhid
 * @param busType
 * @param callback
 * @param cancelback
 * @private
 */
async function _startFlowWithNavigation(
  bizType,
  bizPhid?,
  busType?,
  callback?,
  cancelback?,
  processType?,
  formApprovalUserNo?
) {
  const params: any = iup.isObject(bizType)
    ? bizType
    : { bizType, bizPhid, busType, cancelback, callback, processType, formApprovalUserNo };
  const resp = await iup.request.get({
    url: 'SUP/NavigationCenter/GetProcessBillWorkflow',
    data: {
      billid: params.bizPhid,
      bustype: params.busType
    }
  });
  await _startFlowWithPdKey({
    pdkey: resp.data || null,
    ...params
  });
}

/**
 * 单个送审接口
 * @param bizType
 * @param bizPhid
 * @param callback
 * @param cancelback
 */
async function _startFlow(
  appCode,
  bizCode,
  dataId,
  cuNo,
  orgNo,
  callback,
  cancelback,
  processType,
  formApprovalUserNo
) {
  await _startFlowWithPdKey({
    appCode,
    bizCode,
    dataId,
    cuNo,
    orgNo,
    cancelback,
    callback,
    processType,
    formApprovalUserNo
  });
}

/**,processType
 * 批量送审接口
 * @param bizType
 * @param bizData
 * @param callback
 * @private
 */
async function _batchStartFlow(bizCode, bacthFlowList, callback, cancelback) {
  const params: any = iup.isArray(bacthFlowList) ? bacthFlowList : [];
  if (bacthFlowList.length === 0) {
    await wfAlert(NGLang.alertTitle, NGLang.paramError);
  } else if (bacthFlowList.length === 1) {
    return $WorkFlow.startFlow({
      bizCode,
      dataId: bacthFlowList[0].dataId,
      cuNo: bacthFlowList[0].cuNo,
      orgNo: bacthFlowList[0].orgNo
    });
  } else if (bacthFlowList.length > 50) {
    await wfAlert(NGLang.alertTitle, NGLang.batchStartFlowNumberLimit);
  } else {
    const formData = bacthFlowList.map((i) => {
      return {
        ...i,
        bizCode
      };
    });
    const resp: any = await usingProgress(() =>
      iup.request.body({
        url: 'workflow/processDefinition/getBatchStartProcessExecutionInfo',
        data: {
          formDataIdentityRequests: formData
        }
      })
    );
    if (resp.code === 0) {
      await openWorkFlowBatchStartWin({
        callback,
        cancelback,
        formData,
        data: resp.data.processDefinitions
      });
    } else {
      await wfAlert(NGLang.getPdListError, resp.errorMsg);
    }
  }
}

/**
 * 送审接口,根据pdId筛选，启动流程，一体化资源平台需求
 * @param params
 */
async function _startFlowWithPdId(params: any) {
  const { appCode, bizCode, dataId, pdId, cuNo, orgNo, cancelback } = params;
  if (!appCode || !bizCode) {
    await wfAlert(NGLang.alertTitle, NGLang.paramError);
    return;
  }

  const data: any = { appCode, bizCode, dataId, cuNo, orgNo };

  if (orgNo) {
    data.orgNo = orgNo;
  }
  const res = await usingProgress(() =>
    iup.request.body({
      url: '/workflow/processDefinition/getStartProcessExecutionInfo',
      data: { appCode, bizCode, dataId, cuNo, orgNo }
    })
  );
  if (res.code === 0) {
    const processDefinitions: any = res.data;
    if (processDefinitions.hasRuninfgFlow) {
      await wfAlert(NGLang.alertTitle, NGLang.bizHasRuningProcInst);
      cancelback?.();
      return;
    }
    processDefinitions.processDefinitions = processDefinitions.processDefinitions.filter((item) => {
      return item['id'] === pdId;
    });
    await openWorkFlowStartWin({
      ...params,
      data: processDefinitions,
      autoStart: !!pdId || processDefinitions.autostart
    });
  } else {
    await wfAlert(NGLang.getPdListError, res.errorMsg);
  }
}

/**
 * 工作流api
 */
const $WorkFlow = {
  // 送审
  startFlow(params: {
    appCode?: string;
    bizCode: string;
    dataId: string;
    cuNo?: string;
    orgNo?: string;
    processType?: string;
    formApprovalUserNo?: string;
    successCallback?: Function;
    cancelCallback?: Function;
  }) {
    return new Promise((resolve, reject) => {
      _startFlow(
        params.appCode || '0100',
        params.bizCode,
        params.dataId,
        params.cuNo,
        params.orgNo,
        (...args) => {
          params.successCallback?.(...args);
          resolve(args);
        },
        (...args) => {
          params.cancelCallback?.(...args);
          reject(args);
        },
        params.processType,
        params.formApprovalUserNo
      ).then();
    });
  },
  // 批量送审
  batchStartFlow(params: {
    bizCode: string;
    bacthFlowList: any;
    successCallback?: Function;
    cancelCallback?: Function;
  }) {
    return new Promise((resolve, reject) => {
      _batchStartFlow(
        params.bizCode,
        params.bacthFlowList,
        (...args) => {
          params.successCallback?.(...args);
          resolve(args);
        },
        (...args) => {
          params.cancelCallback?.(...args);
          reject(args);
        }
      ).then();
    });
  },
  startFlowWithNavigation({
    bizType,
    bizPhId,
    busType,
    successCallback,
    cancelCallback,
    processType,
    formApprovalUserNo
  }) {
    return _startFlowWithNavigation(
      bizType,
      bizPhId,
      busType,
      successCallback,
      cancelCallback,
      processType,
      formApprovalUserNo
    ).then();
  },
  // 流程追踪
  showFlowInfo,
  // 通过piId查看流程信息
  showFlowInfoByPiId,
  startFlowWithPdId(params: {
    appCode?: string;
    bizCode: string;
    dataId: string;
    pdId?: string;
    cuNo?: string;
    orgNo?: string;
    successCallback?: Function;
    cancelCallback?: Function;
  }) {
    return new Promise((resolve, reject) => {
      _startFlowWithPdId({
        appCode: params.appCode || '0100',
        bizCode: params.bizCode,
        dataId: params.dataId,
        cuNo: params.cuNo,
        orgNo: params.orgNo,
        pdId: params.pdId,
        callback: (...args) => {
          params.successCallback?.(...args);
          resolve(args);
        },
        cancelback: (...args) => {
          params.cancelCallback?.(...args);
          reject(args);
        }
      }).then();
    });
  }
};

iup.registerExternal({
  getWorkFlowSdk() {
    return $WorkFlow;
  }
});

export { default as WorkFlowPanel } from './WorkFlowPanel';
export { $WorkFlow };
export type WorkFlowApiType = typeof $WorkFlow;
